package com.newture.lxz.i18n;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

/**
 * @author xiao.hu
 * @date 2021-09-26
 * @apiNote
 */
@Component
public class I18nTranslator {

    private static MessageSource messageSource;

    /**
     * 必须要有 messages.properties 文件才不会导致 Empty MessageSource
     * messages_en_US.properties
     * messages_zh_CN.properties
     * 才是附加的
     *
     * @param messageSource
     */
    public I18nTranslator(MessageSource messageSource) {
        I18nTranslator.messageSource = messageSource;
    }

    /**
     * 获取单个国际化翻译值
     */
    public static String get(String msgKey) {
        try {
            return messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return msgKey;
        }
    }
}
